
package net.swa.dewei.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import net.swa.dewei.beans.entity.DingDanCard;
import net.swa.dewei.beans.entity.DingDanCardGoods;
import net.swa.dewei.beans.entity.LifeGoods;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.vo.VoListPage;
import net.swa.dewei.service.LifeGoodsService;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.JsonResult;

@Service("lifeGoodsService")
public class LifeGoodsServiceImpl extends HibernateDaoSupport implements LifeGoodsService
{

    @Override
    public LifeGoods queryById(Long id)
    {
        LifeGoods m = null;
        Session session = getCurrentSession();
        m = (LifeGoods) session.get(LifeGoods.class, id);
        return m;
    }

    @SuppressWarnings("unchecked")
    @Override
    public JsonResult<LifeGoods> queryPage(String name , String pinpai , String guige , int currentPage , int pageSize , String orderBy , String orderType)
    {
        JsonResult<LifeGoods> json = new JsonResult<LifeGoods>();
        List<LifeGoods> list = null;
        StringBuilder hql = new StringBuilder();
        hql.append("from LifeGoods where 1=1 ");
        if (!StringUtils.isBlank(name))
        {
            hql.append(" and name like :name ");
        }

        if (!StringUtils.isBlank(pinpai))
        {
            hql.append(" and pinpai like :pinpai ");
        }
        if (!StringUtils.isBlank(guige))
        {
            hql.append(" and guige like :guige ");
        }
        if (!!StringUtils.isEmpty(orderBy))
        {
            hql.append(" order by " + orderBy + " " + orderType);
        }
        else
        {
            hql.append(" order by  sort ");
        }
        Query query = getCurrentSession().createQuery(hql.toString());

        if (!StringUtils.isBlank(name))
        {
            query.setString("name", "%" + name + "%");
        }

        if (!StringUtils.isBlank(pinpai))
        {
            query.setString("pinpai", "%" + pinpai + "%");
        }
        if (!StringUtils.isBlank(guige))
        {
            query.setString("guige", "%" + guige + "%");
        }
        if (pageSize > 0)
        {
            int from = (currentPage - 1) * pageSize;
            query.setFirstResult(from);
            query.setMaxResults(pageSize);
        }
        list = query.list();
        // 查询满足条件的总数量
        query = getCurrentSession().createQuery("select count(*) " + hql);
        if (!StringUtils.isBlank(name))
        {
            query.setString("name", "%" + name + "%");
        }

        if (!StringUtils.isBlank(pinpai))
        {
            query.setString("pinpai", "%" + pinpai + "%");
        }
        if (!StringUtils.isBlank(guige))
        {
            query.setString("guige", "%" + guige + "%");
        }
        if (pageSize > 0)
        {
            int totalCount = ((Number) (query.iterate().next())).intValue();
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            json.setTotalSize(totalCount);
            json.setTotalPage(totalPage);
            json.setPageSize(pageSize);
            json.setCurrentPage(currentPage);
        }

        json.setResult(list);
        return json;
    }

    @Override
    public boolean add(LifeGoods model)
    {
        if (null != model)
        {
            Session session = getCurrentSession();
            model.setCrateDate(DateUtils.getCurrDate(null));
            model.setUpdateDate(DateUtils.getCurrDate(null));
            model.setStatus(BuzConst.STATUS_YES);
            session.save(model);
            return true;
        }
        else
        {
            return false;
        }

    }

    @Override
    public boolean update(LifeGoods model)
    {
        if (model != null)
        {
            if (model.getId() != null)
            {
                Session session = getCurrentSession();
                model.setUpdateDate(DateUtils.getCurrDate(null));
                session.update(model);
                return true;
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> batchUpdateXiajia(Long[] ids)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        map.put("message", "没有要下架商品");
        if (null != ids && ids.length > 0)
        {
            String sql = "update t_life set status=0  where id=:id";
            Session session = getCurrentSession();
            Query q = session.createSQLQuery(sql);
            for (Long id : ids)
            {
                q.setLong("id", id);
                q.executeUpdate();
            }
            map.put("success", true);
            map.put("message", "");
        }
        return map;
    }

    @Override
    public Map<String, Object> updateState(Long id , Integer status)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        map.put("message", "没有要下架商品");
        if (null != id && null != status)
        {
            if (1 == status || 0 == status)
            {
                String sql = "update LifeGoods set status=:status  where id=:id";
                Session session = getCurrentSession();
                Query q = session.createQuery(sql);
                q.setLong("id", id);
                q.setInteger("status", status);
                q.executeUpdate();
                map.put("success", true);
                map.put("message", "");
            }
            else
            {
                map.put("message", "产品状态错误");
            }
        }
        return map;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<LifeGoods> queryList(String name , int status , int max)
    {
        List<LifeGoods> list = null;
        StringBuilder hql = new StringBuilder();
        hql.append("from LifeGoods where 1=1 and status=:status ");

        if (!StringUtils.isBlank(name))
        {
            hql.append(" and name like :name ");
        }

        hql.append(" order by  sort ");
        Query query = getCurrentSession().createQuery(hql.toString());
        query.setInteger("status", status);
        if (!StringUtils.isBlank(name))
        {
            query.setString("name", "%" + name + "%");
        }
        query.setMaxResults(max);
        list = query.list();
        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    public VoListPage<LifeGoods> queryVoList(String name , int status , int max)
    {
        VoListPage<LifeGoods> map = new VoListPage<LifeGoods>();

        List<LifeGoods> list = null;
        StringBuilder hql = new StringBuilder();
        hql.append("from LifeGoods where 1=1 and status=:status ");

        if (!StringUtils.isBlank(name))
        {
            hql.append(" and name like :name ");
        }

        hql.append(" order by  id desc ");
        Query query = getCurrentSession().createQuery(hql.toString());
        query.setInteger("status", status);
        if (!StringUtils.isBlank(name))
        {
            query.setString("name", "%" + name + "%");
        }
        query.setMaxResults(max);
        list = query.list();
        if (null != list && list.size() > 0)
        {
            LifeGoods o = list.get(list.size() - 1);
            map.setSuccess(true);
            map.setResult(list);
            map.setCurrentId(o.getId());
            map.setHasNext(true);
        }
        else
        {
            map.setSuccess(false);
            map.setResult(list);
            map.setHasNext(false);
        }
        return map;
    }

    @SuppressWarnings("unchecked")
    @Override
    public VoListPage<LifeGoods> queryVoListByLastId(String name , int status , int max , long id)
    {
        VoListPage<LifeGoods> map = new VoListPage<LifeGoods>();

        List<LifeGoods> list = null;
        StringBuilder hql = new StringBuilder();
        hql.append("from LifeGoods where 1=1 and status=:status and id<:id ");

        if (!StringUtils.isBlank(name))
        {
            hql.append(" and name like :name ");
        }

        hql.append(" order by  id desc ");
        Query query = getCurrentSession().createQuery(hql.toString());
        query.setInteger("status", status);
        query.setLong("id", id);
        if (!StringUtils.isBlank(name))
        {
            query.setString("name", "%" + name + "%");
        }
        query.setMaxResults(max);
        list = query.list();
        if (null != list && list.size() > 0)
        {
            LifeGoods o = list.get(list.size() - 1);
            map.setSuccess(true);
            map.setResult(list);
            map.setCurrentId(o.getId());
            map.setHasNext(true);
        }
        else
        {
            map.setSuccess(false);
            map.setResult(list);
            map.setHasNext(false);
        }
        return map;
    }

    @Override
    public List<LifeGoods> queryBuyList(Long[] ids , Integer[] buyNums)
    {
        Session session = getCurrentSession();
        List<LifeGoods> list = new ArrayList<LifeGoods>();
        for (int i = 0; i < ids.length && i < buyNums.length; i++)
        {
            LifeGoods o = (LifeGoods) session.get(LifeGoods.class, ids[i]);
            if (null != o)
            {
                if (null != buyNums && null != buyNums[i])
                {
                    o.setBuyNum(buyNums[i]);
                }
                else
                {
                    o.setBuyNum(buyNums[1]);
                }
                list.add(o);
            }
        }
        return list;
    }

    @Override
    public DingDanCard saveDingdanModel(DingDanCard d , Long[] ids , Integer[] buyNums , String cardPaytypeSm)
    {
        Session session = getCurrentSession();
        final String ds = DateUtils.getCurrDate("yyyyMMddHHmmss");
        String r = null;
        d.setBuyType(cardPaytypeSm);
        if (null != ids && ids.length > 0)
        {
            d.setCrateDate(DateUtils.getCurrDate(null));
            d.setState(BuzConst.CARD_DINGDAN_STATES0);
            session.save(d);
            r = ds + d.getId();
            d.setDingDanUid(r);
            double totalMoney = 0;
            List<DingDanCardGoods> goods = new ArrayList<DingDanCardGoods>();
            for (int i = 0; i < ids.length && i < buyNums.length; i++)
            {
                LifeGoods o = (LifeGoods) session.get(LifeGoods.class, ids[i]);
                if (null != o)
                {
                    if (null != buyNums && null != buyNums[i])
                    {
                        DingDanCardGoods zdd = new DingDanCardGoods();
                        zdd.setFid(d.getId());
                        zdd.setGoodsId(ids[i]);
                        zdd.setGoodsName(o.getName());
                        zdd.setImageUrl(o.getImgUrl());
                        zdd.setNum(buyNums[i]);
                        zdd.setPrice(o.getCardprice());
                        zdd.setGuige(o.getGuige());
                        zdd.setPinpai(o.getPinpai());
                        session.save(zdd);
                        totalMoney = BuzConst.add(totalMoney, BuzConst.mul(o.getCardprice(), buyNums[i]));
                        goods.add(zdd);
                    }
                }
                //要把该微信号该产品从购物车移除
                if (!StringUtils.isBlank(d.getUserId()))
                {
                    Query q = session.createQuery(" delete from LifeCardCar where goodsId=:goodsId and wxid=:wxid");
                    q.setLong("goodsId", ids[i]);
                    q.setString("wxid", d.getUserId());
                    q.executeUpdate();
                }
            }
            d.setGoodsPrice(totalMoney);
            session.update(d);
            d.setGoods(goods);

        }
        if (null != d.getMendianId())
        {
            MenDian mend = (MenDian) session.get(MenDian.class, d.getMendianId());
            if (null != mend)
            {
                d.setMendAddr(mend.getAddress());
                d.setMendImgUrl(mend.getImageUrl());
                d.setMendName(mend.getName());
                d.setMendLxr(mend.getLxr());
                d.setMendLxTel(mend.getLxrTel());
            }
        }
        return d;
    }
}